package com.lsj.spring.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/6/26 16:40
 * mapperScan指定要变成实现类的接口所在的包
 * configuration算是把该类作为spring的xml配置文件中的<bean/>
 * 加上bean注册bean
 */
@MapperScan("com.lsj.spring.mapper")
@Configuration
public class MybatisConfiguration {
    private final JdbcConfig jdbcConfig;

    public MybatisConfiguration(JdbcConfig jdbcConfig) {
        this.jdbcConfig = jdbcConfig;
    }

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcConfig.getDriver());
        dataSource.setUrl(jdbcConfig.getUrl());
        dataSource.setUsername(jdbcConfig.getUsername());
        dataSource.setPassword(jdbcConfig.getPassword());
        dataSource.setMaxActive(jdbcConfig.getMax());
        dataSource.setMinIdle(jdbcConfig.getMin());
        return dataSource;
    }

    /**'
     * Qualifier注解与我们要使用的特定spring bean的名称一起安装
     * 根据其中的value是要注入的bean
     * @param dataSource 注入的bean
     * @return 返回一个工厂类
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("dataSource") DruidDataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}
